import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QSlider,
                             QFileDialog, QLabel, QVBoxLayout, QHBoxLayout,
                             QWidget, QStyle)
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtCore import Qt, QUrl


class VideoPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("视频播放器")
        self.setGeometry(100, 100, 800, 600)

        # 创建媒体播放器对象
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        # 创建视频显示部件
        self.videoWidget = QVideoWidget()

        # 创建打开文件按钮
        self.openButton = QPushButton("打开文件")
        self.openButton.clicked.connect(self.openFile)

        # 创建播放/暂停按钮
        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.playPause)

        # 创建进度条
        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        # 创建音量控制
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximumWidth(100)
        self.volumeSlider.setRange(0, 100)
        self.volumeSlider.setValue(70)
        self.volumeSlider.valueChanged.connect(self.setVolume)

        # 创建时间标签
        self.timeLabel = QLabel("00:00/00:00")

        # 创建布局
        controlLayout = QHBoxLayout()
        controlLayout.addWidget(self.openButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.timeLabel)
        controlLayout.addWidget(self.volumeSlider)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.videoWidget)
        mainLayout.addLayout(controlLayout)

        # 创建中心部件
        centralWidget = QWidget()
        centralWidget.setLayout(mainLayout)
        self.setCentralWidget(centralWidget)

        # 设置视频部件
        self.mediaPlayer.setVideoOutput(self.videoWidget)

        # 连接信号和槽
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        # 设置初始音量
        self.mediaPlayer.setVolume(70)

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(self, "打开视频文件", "",
                                                  "视频文件 (*.mp4 *.avi *.mov *.mkv);;所有文件 (*)")

        if fileName != '':
            self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)
            self.mediaPlayer.play()  # 打开文件后自动播放

    def playPause(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        # 避免在用户拖动进度条时更新进度，防止卡顿
        if not self.positionSlider.isSliderDown():
            self.positionSlider.setValue(position)
        # 更新时间标签
        current_time = self.formatTime(position)
        total_time = self.formatTime(self.mediaPlayer.duration())
        self.timeLabel.setText(f"{current_time}/{total_time}")

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def setVolume(self, volume):
        self.mediaPlayer.setVolume(volume)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.timeLabel.setText(f"错误: {self.mediaPlayer.errorString()}")
        print(f"媒体播放器错误: {self.mediaPlayer.errorString()}")

    def formatTime(self, ms):
        # 将毫秒转换为 HH:MM:SS 格式，支持更长时间
        total_seconds = ms // 1000
        hours = total_seconds // 3600
        minutes = (total_seconds % 3600) // 60
        seconds = total_seconds % 60
        if hours > 0:
            return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
        else:
            return f"{minutes:02d}:{seconds:02d}"


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 确保中文显示正常
    font = app.font()
    font.setFamily("SimHei")
    app.setFont(font)

    player = VideoPlayer()
    player.show()
    sys.exit(app.exec_())    